package cn.lixiaodan.hqlbuilder.model;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.lixiaodan.hqlbuilder.util.AppPrefs;

/**
 * 类实体封装
 * 
 * @author lixiaodan
 * 
 */
public class ClassModel {
	private String name;
	private String shortName;
	private List<String> fields = new ArrayList<String>();
	private static final String EXCLUDE_FIELD[] = AppPrefs.getString(
			"EXCLUDE_FIELD").split(",");

	public ClassModel() {
	}

	public ClassModel(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public String getShortName() {
		return shortName;
	}

	public void setShortName(String shortName) {
		this.shortName = shortName;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<String> getFields() {
		return fields;
	}

	public void setFields(List<String> fields) {
		this.fields = fields;
	}

	public void add(String field) {
		this.fields.add(field);
	}

	public void query() {
		this.fields.clear();
		try {
			Class clszz = Class.forName(this.name);
			this.shortName = clszz.getSimpleName();

			Method[] marray = clszz.getMethods();
			for (int i = 0; i != marray.length; i++) {
				Method mth = marray[i];
				if (mth.getName().startsWith("get")
						&& mth.getParameterTypes().length == 0) {
					char marr[] = mth.getName().toCharArray();
					if (marr.length <= 3)
						continue;
					marr[3] = Character.toLowerCase(marr[3]);
					String name = new String(marr, 3, marr.length - 3);
					boolean isExclude = false;
					for (int a = 0; a != EXCLUDE_FIELD.length; a++) {
						isExclude = isExclude || EXCLUDE_FIELD[a].equals(name);
					}
					if (!isExclude)
						this.fields.add(name);
				}
			}
			Collections.sort(this.fields, new Comparator<String>() {
				@Override
				public int compare(String o1, String o2) {
					return o1.compareTo(o2);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		return this.getShortName();
	}
}
